package com.example.myproject;

import com.example.myproject.Entity.LoginInfo;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@Aspect
@Component
public class LoginLoggingAspect {

    private final LoginInfoRepository loginInfoRepository;
    private final HttpServletRequest request;

    @Autowired
    public LoginLoggingAspect(LoginInfoRepository loginInfoRepository, HttpServletRequest request) {
        this.loginInfoRepository = loginInfoRepository;
        this.request = request;
    }

    @Pointcut("@annotation(com.example.myproject.MyAnnotation)")
    public void loginPointcut() {
    }

    @AfterReturning(pointcut = "loginPointcut()", returning = "result")
    public void logLogin(JoinPoint joinPoint, Object result) {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        // 获取登录方法的参数
        Object[] args = joinPoint.getArgs();
        String username = (String) args[0];

        // 记录登录日志
        LoginInfo loginInfo = new LoginInfo();
        loginInfo.setUsername(username);
        String clientIp = getClientIp(request);
        loginInfo.setIp(clientIp);
        loginInfo.setLoginTime(new Date());
        loginInfoRepository.save(loginInfo);
    }

    private String getClientIp(HttpServletRequest request) {
        String ipAddress = request.getHeader("X-Forwarded-For");
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getRemoteAddr();
        }
        return ipAddress;
    }
}
